﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Character : MonoBehaviour {

    public int MaxHP;
    public Color DamageColor;
    public float AttackRate = 1;
    public int Attack = 10;

    public Renderer[] renderers;
    protected Color currentColor;
    protected List<Color> currentColors = new List<Color>();
    protected float timer;
    protected float cooldown;

    public enum State : int
    {
        Alive,
        Dead,
    }

    public State state = State.Alive;

    int _HP;
    public int HP
    {
        get { return _HP; }
        set
        {
            _HP = value;
            _HP = Mathf.Clamp(HP, 0, MaxHP);
            if (_HP == 0)
            {
                gameObject.SetActive(false);
            }
        }
    }

    public virtual void Awake()
    {
        HP = MaxHP;
        cooldown = 1/AttackRate;
        timer = 0;
        if (renderer)
        {
            currentColor = transform.renderer.material.color;
        }
        else
        {
            renderers = GetComponentsInChildren<Renderer>();
            //Debug.Log(renderers.Length);
            for (int i = 0; i < renderers.Length; i++)
            {
                if (renderers[i])
                {
                    currentColors.Add(renderers[i].material.color);
                }
            }
        }
    }

    public virtual void Update()
    {
        timer += Time.deltaTime;

        if (renderer)
        {
            transform.renderer.material.color = Color.Lerp(transform.renderer.material.color, currentColor, 10 * Time.deltaTime);
        }
        else
        {
            
            for (int i = 0; i < renderers.Length; i++)
            {
                if (renderers[i])
                    renderers[i].material.color = Color.Lerp(renderers[i].material.color, currentColors[i], 10 * Time.deltaTime);
            }
        }
    }

    public virtual void TakeDamage(int Damage, Vector3 hitpoint)
    {
        if (renderer)
        {
            transform.renderer.material.color = DamageColor;
        }
        else
        {
            for (int i = 0; i < renderers.Length; i++)
            {
                if (renderers[i])
                    renderers[i].material.color = DamageColor;
            }
        }

        HP -= Damage;
    }
}
